<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>手风琴效果(css+js)</title>
  </head>
  <body>
    <div class="accordion">
      <div class="accordion-item">
        <div class="accordion-header">
          <span>标题 1</span>
          <span class="icon">▼</span>
        </div>
        <div class="accordion-content">
          <p>内容 1：这里是手风琴的内容部分。</p>
        </div>
      </div>
      <div class="accordion-item">
        <div class="accordion-header">
          <span>标题 2</span>
          <span class="icon">▼</span>
        </div>
        <div class="accordion-content">
          <p>内容 2：这里是手风琴的内容部分。</p>
        </div>
      </div>
      <div class="accordion-item">
        <div class="accordion-header">
          <span>标题 3</span>
          <span class="icon">▼</span>
        </div>
        <div class="accordion-content">
          <p>内容 3：这里是手风琴的内容部分。</p>
        </div>
      </div>
    </div>

  </body>

  <style>
    body {
      font-family: Arial, sans-serif;
      background-color: #f4f4f4;
      padding: 20px;
    }

    .accordion {
      border: 1px solid #ccc;
      border-radius: 5px;
      overflow: hidden;
    }

    .accordion-item {
      border-bottom: 1px solid #ccc;
    }

    .accordion-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px;
      background-color: #fff;
      cursor: pointer;
      transition: background-color 0.3s ease;
    }

    .accordion-header:hover {
      background-color: #eaeaea;
    }

    .icon {
      transition: transform 0.3s ease;
    }

    .accordion-content {
      max-height: 0;
      overflow: hidden;
      transition: max-height 0.3s ease;
      padding: 0 15px;
      background-color: #f9f9f9;
    }

    .active .icon {
      transform: rotate(180deg);
    }
  </style>

  <script>
    document.querySelectorAll('.accordion-header').forEach(header => {
      header.addEventListener('click', function () {
        const item = this.parentElement;
        const content = item.querySelector('.accordion-content');

        // 先关闭其他打开的手风琴项
        document.querySelectorAll('.accordion-item.active').forEach(activeItem => {
          if (activeItem !== item) {
            activeItem.classList.remove('active');
            const activeContent = activeItem.querySelector('.accordion-content');
            activeContent.style.maxHeight = '0';
          }
        });

        // 切换当前项的状态
        item.classList.toggle('active');

        // 更新内容的最大高度
        if (item.classList.contains('active')) {
          content.style.maxHeight = content.scrollHeight + 'px';
        } else {
          content.style.maxHeight = '0';
        }
      });
    });
  </script>
</html>
